package com.hjk.common.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.UUID;

@Slf4j
public class TokenInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("进入了幂等校验拦截器 : 当前方法 : {}" ,handler.getClass());
        log.info("");
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        Token annotation = method.getAnnotation(Token.class);

        if (annotation != null) {
            //生成token到session中
            boolean needSaveSession = annotation.save();
            if (needSaveSession) {
                String uuid = UUID.randomUUID().toString();
                log.debug("提交生成除令牌" + uuid);
                request.getSession(false).setAttribute("token", uuid);
            }

            //删除token
            boolean needRemoveSession = annotation.remove();
            if (needRemoveSession) {
                if (isRepeatSubmit(request)) {
                    log.info("访问拒绝");
                    return false;
                }
                //当前session中的token和此次请求的token相等则删除
                log.debug("提交移除令牌" + request.getSession(false).getAttribute("token"));
                request.getSession(false).removeAttribute("token");
            }
        }
        return true;
    }

    private boolean isRepeatSubmit(HttpServletRequest request) {
        //从session获取TOKEN
        String serverToken = (String) request.getSession(false).getAttribute("token");
        if (serverToken == null) {
            return true;
        }
        //当前请求的token
        String clinetToken = request.getParameter("token");
        if (clinetToken == null) {
            return true;
        }

        //如果不相等
        if (!serverToken.equals(clinetToken)) {
            return true;
        }
        return false;
    }
}